﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Traceability.API.Applications.Command.AquacultureCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.AquacultureCommandHandler
{
    public class FarmAddCommandHandler : IRequestHandler<FarmAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Farm> farmRepository;
        private readonly IMapper mapper;

        public FarmAddCommandHandler(IBaseRepository<Farm> farmRepository, IMapper mapper)
        {
            this.farmRepository = farmRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(FarmAddCommand request, CancellationToken cancellationToken)
        {
            var model = mapper.Map<Farm>(request);
            if (request.Id != 0)
            {
                model.UpDataUserId = request.CreateUserId;
                model.UpDataTime = DateTime.Now;
            }
            int count= await farmRepository.Update(model);

            APIResult<int> result = new APIResult<int>();
            if (count==0)
            {
                result.Code = EnumCode.File;
                result.Msg = "保存失败";
            }
            else
            {
                result.Code = EnumCode.Ok;
                result.Msg = "保存成功";
                result.Data = count;
            }

            return await Task.FromResult(result);
        }
    }
}
